﻿

Imports System.ComponentModel
Imports HslControls
Imports HslCommunication.LogNet
Imports System.Timers

Public Class frmLHJList

    Private objHWSetting As New clsHWSetting

    Private _selectedLHJ As String
    Private _selectedClose As Boolean = False
    Private logfile As ILogNet
    Private th As System.Threading.Thread
    Private th_stop As Boolean = False
    Private WithEvents MoveDataTimer As System.Timers.Timer
    Delegate Sub setMontLHJEventHandler(_lhj As String)
    Private Function CurrentDomain_AssemblyResolve(sender As Object, args As ResolveEventArgs) As System.Reflection.Assembly
        Dim dllName As String = If(args.Name.Contains(","), args.Name.Substring(0, args.Name.IndexOf(","c)), args.Name.Replace(".dll", ""))
        dllName = dllName.Replace(".", "_")
        If dllName.EndsWith("_resources") Then
            Return Nothing
        End If
        Dim rm As New System.Resources.ResourceManager([GetType].Namespace & ".Resources", System.Reflection.Assembly.GetExecutingAssembly())
        Dim bytes As Byte() = DirectCast(rm.GetObject(dllName), Byte())
        Return System.Reflection.Assembly.Load(bytes)
    End Function
    Private Sub setMonitLHJ(_lhj As String)
        Try
            tsmiLHJ.Text = _lhj
        Catch ex As Exception
            logfile.WriteError("setMonitLHJ:", ex.Message)
        End Try

    End Sub
    Dim objsetMoniter As New setMontLHJEventHandler(AddressOf setMonitLHJ)

    Public Sub New()
        AddHandler AppDomain.CurrentDomain.AssemblyResolve, New ResolveEventHandler(AddressOf CurrentDomain_AssemblyResolve)

        ' 此调用是设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。

    End Sub

    Private Sub doActive()
        Dim ping = New Net.NetworkInformation.Ping()
        While Not th_stop
            Dim allLHJ As DataTable = objHWSetting.selectALL()
            For Each lhj As DataRow In allLHJ.Rows

                Me.Invoke(objsetMoniter, lhj("equip_id"))
                'ToolStripStatusLabel2.Text = lhj("equip_id")
                'Application.DoEvents()
                Try
                    'If My.Computer.Network.Pixng(lhj("ip")) = False Then
                    Dim pingResult As Net.NetworkInformation.PingReply = ping.Send(lhj("ip"))
                    If Not pingResult.Status = Net.NetworkInformation.IPStatus.Success Then
                        '硫化机开关机记录--关机
                        Dim rtn As Integer = objHWSetting.record_LHJ_Status(lhj("equip_id"), 2)

                        If lhj("status") <> 2 Then
                            logfile.WriteInfo("frmLHJList", lhj("equip_id") & ":Ping 线程 状态改成2")
                            objHWSetting.setLHJOnOff(lhj("equip_id"), 2)
                            logfile.WriteInfo(lhj("equip_id") & "--保存记录=>", 2)
                        End If
                    Else
                        '硫化机开关机记录--开机
                        Dim rtn As Integer = objHWSetting.record_LHJ_Status(lhj("equip_id"), 0)

                        If lhj("status") = 2 Then
                            logfile.WriteInfo(lhj("equip_id") & "--保存记录=>", 0)
                            If DBNULLtoBlank(lhj("prod_id")) <> "" Then
                                objHWSetting.setLHJOnOff(lhj("equip_id"), 1)
                                logfile.WriteInfo("frmLHJList", lhj("equip_id") & ":Ping 线程 状态改成1")
                            Else
                                objHWSetting.setLHJOnOff(lhj("equip_id"), 0)
                                logfile.WriteInfo("frmLHJList", lhj("equip_id") & ":Ping 线程 状态改成0")
                            End If
                        End If
                    End If
                Catch ex As Exception
                    logfile.WriteError("frmLHJList", lhj("equip_id") & ":Ping 失败" & lhj("ip") & vbCrLf & ex.Message)
                End Try
                Threading.Thread.Sleep(500)
            Next

        End While
    End Sub

    Public Property SelectedLHJ As String
        Get
            Return _selectedLHJ
        End Get
        Set(value As String)
            _selectedLHJ = value
        End Set
    End Property

    Public Property SelectedClose As Boolean
        Get
            Return _selectedClose
        End Get
        Set(value As Boolean)
            _selectedClose = value
        End Set
    End Property

    Private Sub frmLHJList_Load(sender As Object, e As EventArgs) Handles Me.Load

        If Not HslCommunication.Authorization.SetAuthorizationCode("e3e27344-1a9f-4d8b-b4fc-da5cae4b99bf") Then

        End If
        If Not HslControls.Authorization.SetAuthorizationCode("ce5ade06-6f14-4b0d-b9c2-0d625664dc3f") Then

        End If

        MoveDataTimer = New Timer(60 * 1000)

        MoveDataTimer.Start()
        logfile = New LogNetDateTime(Application.StartupPath & "\\Logs", GenerateMode.ByEveryDay)
        connectDB()

        setTLP()
        lhjLoad()

        th = New Threading.Thread(AddressOf doActive)
        'Control.CheckForIllegalCrossThreadCalls = False
        th.Start()
    End Sub

    Public Sub connectDB()
        'イニシャルファイル情報取得
        g_szInitFileName = My.Application.Info.DirectoryPath & "\LHJServer.ini"

        g_Server.szDrive = GetIniFile("SERVER", "DRIVE", "PostgreSQL ANSI", g_szInitFileName)
        g_Server.szIPadr = GetIniFile("SERVER", "IP", "", g_szInitFileName)
        g_Server.szDbn = GetIniFile("SERVER", "DBN", "ZHENANSF", g_szInitFileName)
        g_Server.szUid = GetIniFile("SERVER", "UID", "sa", g_szInitFileName)
        g_Server.szPas = GetIniFile("SERVER", "PAS", "sa", g_szInitFileName)
        g_Server.iOver = CInt(GetIniFile("SERVER", "OVER", "-1", g_szInitFileName))

        '得到当前用户名
        g_LoginUser = GetIniFile("LOGIN", "user", "admin", g_szInitFileName)

        If False = g_fDBconnect And 0 = g_iDBconnResult Then
            If "" = g_Server.szIPadr Or "0.0.0.0" = g_Server.szIPadr Then
            Else
                g_fDBconnect = True

                'データベース接続
                With g_Server
                    g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    If 1 <> g_iDBconnResult Then
                        .szDrive = CStr(IIf("PostgreSQL" = .szDrive, "PostgreSQL ANSI", "PostgreSQL"))
                        g_iDBconnResult = DBacs.Connect(.szDrive, .szIPadr, .szDbn, .szUid, .szPas, .iOver)
                    End If
                End With
            End If
        End If

        setAllErrMsg()
    End Sub

    Private Sub frmLHJList_Closed(sender As Object, e As EventArgs) Handles Me.Closed
        Try
            MoveDataTimer.Stop()
            If th.IsAlive Then th.Abort()
            DBacs.Disconnect()
        Catch ex As Exception
            logfile.WriteError("frmLHJList_Closed:", ex.Message)
        End Try

    End Sub
    Private Sub setTLP()
        Dim maxRow As Integer = 0
        Dim maxCol As Integer = 0
        Try
            objHWSetting.getMaxRowCol(maxRow, maxCol)
            If maxRow > 0 And maxCol > 0 Then
                Me.TLP.RowStyles.Clear()
                Me.TLP.ColumnStyles.Clear()
                TLP.RowCount = maxRow
                TLP.ColumnCount = maxCol
                For i As Integer = 0 To maxRow
                    Me.TLP.RowStyles.Add(New System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100 / maxRow))
                Next
                For i As Integer = 0 To maxCol
                    Me.TLP.ColumnStyles.Add(New System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100 / maxCol))
                Next
            End If

        Catch ex As Exception
            logfile.WriteError("setTLP:", ex.Message)
        End Try


    End Sub
    Private Sub lhjLoad()

        Dim dtLHJ As DataTable
        'Dim dtLHJDetail As DataTable
        '检索所有硫化机
        dtLHJ = objHWSetting.selectAllLHJ
        '清空画面现有硫化机
        TLP.Controls.Clear()
        Dim lhj(dtLHJ.Rows.Count) As ucLHJ
        Dim _localIP As String = GetIPAddr()
        Try
            '循环所有硫化机
            For i As Integer = 0 To dtLHJ.Rows.Count - 1
                '将硫化机组件显示到画面上

                Dim st As ucLHJ.LHJ_STATUS '= ucLHJ.LHJ_STATUS.LOSE_CONNECT
                If DBNULLtoBlank(dtLHJ(i)("loc_row")) <> "" Then
                    Dim _row As String = dtLHJ(i)("loc_row")
                    Dim _col As String = dtLHJ(i)("loc_col")

                    If dtLHJ(i)("status") = "0" Then
                        st = ucLHJ.LHJ_STATUS.EMPTY      '空闲
                        lhj(i) = New ucLHJ(st, _row, _col, dtLHJ(i)("equip_id"), "", dtLHJ(i)("equip_id"))
                        'lhj(i).Interval = 0
                    ElseIf dtLHJ(i)("status") = "1" Then
                        st = ucLHJ.LHJ_STATUS.BUSY      '忙
                        lhj(i) = New ucLHJ(st, _row, _col, dtLHJ(i)("equip_id"), DBNULLtoBlank(dtLHJ(i)("prod_id")), dtLHJ(i)("equip_id"))
                        'Dim _interval As Integer = 0
                        'If Not IsDBNull(dtLHJ(i)("prod_spec_id")) Then
                        '    _interval = objHWSetting.getSpecIntervalbySpecID(dtLHJ(i)("prod_spec_id"))
                        'End If
                        'lhj(i).Interval = _interval
                    ElseIf dtLHJ(i)("status") = "2" Then
                        st = ucLHJ.LHJ_STATUS.LOSE_CONNECT  '失联
                        lhj(i) = New ucLHJ(st, _row, _col, dtLHJ(i)("equip_id"), "", dtLHJ(i)("equip_id"))
                        'lhj(i).Interval = 0 '30 * 1000 '半分钟
                    ElseIf dtLHJ(i)("status") = "3" Then
                        st = ucLHJ.LHJ_STATUS.WAIT_OUT      '要出炉
                        lhj(i) = New ucLHJ(st, _row, _col, dtLHJ(i)("equip_id"), DBNULLtoBlank(dtLHJ(i)("prod_id")), dtLHJ(i)("equip_id"))
                        'Dim _interval As Integer = 0
                        'If Not IsDBNull(dtLHJ(i)("prod_spec_id")) Then
                        '    _interval = objHWSetting.getSpecIntervalbySpecID(dtLHJ(i)("prod_spec_id"))
                        'End If
                        'lhj(i).Interval = _interval
                    ElseIf dtLHJ(i)("status") = "4" Then
                        st = ucLHJ.LHJ_STATUS.ERR           '温度或压力Error
                        lhj(i) = New ucLHJ(st, _row, _col, dtLHJ(i)("equip_id"), DBNULLtoBlank(dtLHJ(i)("prod_id")), dtLHJ(i)("equip_id"))
                        'Dim _interval As Integer = 0
                        'If Not IsDBNull(dtLHJ(i)("prod_spec_id")) Then
                        '    _interval = objHWSetting.getSpecIntervalbySpecID(dtLHJ(i)("prod_spec_id"))
                        'End If
                        'lhj(i).Interval = _interval
                    ElseIf dtLHJ(i)("status") = "5" Then
                        st = ucLHJ.LHJ_STATUS.REPAIRS      '维修
                        lhj(i) = New ucLHJ(st, _row, _col, dtLHJ(i)("equip_id"), "", dtLHJ(i)("equip_id"))
                        'lhj(i).Interval = 0 '30 * 1000
                    End If

                    If IsNothing(lhj(i)) = False Then

                        lhj(i).ServerIp = _localIP
                        lhj(i).ServerPort = "2000"
                        lhj(i).LhjIp = dtLHJ(i)("ip")
                        lhj(i).LhjPort = CInt(dtLHJ(i)("port"))
                        lhj(i).Spec_ID = DBNULLtoBlank(dtLHJ(i)("prod_spec_id"))
                        lhj(i).FatherOBJ = Me
                        lhj(i).LogFile = logfile

                        lhj(i).startMonitor()
                        TLP.Controls.Add(lhj(i), _col - 1, _row - 1)

                        Me.Refresh()
                    End If

                End If

            Next
        Catch ex As Exception
            logfile.WriteError("lhjLoad:", ex.Message)
        End Try
    End Sub


    'Private Sub tmrRe_Tick(sender As Object, e As EventArgs) Handles tmrRe.Tick
    '    'For i As Integer = 0 To TLP.Controls.Count - 1
    '    '    Dim usr As ucLHJ = TLP.Controls(i)
    '    '    If usr.Status = ucLHJ.LHJ_STATUS.LOSE_CONNECT Or
    '    '        usr.Status = ucLHJ.LHJ_STATUS.EMPTY Then
    '    '        usr.lblLHJ_No.ForeColor = Color.Purple
    '    '        Me.Refresh()
    '    '        usr.check()
    '    '    End If
    '    'Next
    '    Me.Refresh()
    'End Sub
    Private Sub menuItemClose_Click(sender As Object, e As EventArgs) Handles menuItemClose.Click
        If MsgBox("如关闭系统，则停止监控硫化机！" & vbCrLf & "确定要关闭吗？", 4, Me.Text) = MsgBoxResult.Yes Then
            RemoveHandler Me.Closing, AddressOf frmLHJList_Closing
            NotifyIcon1.Dispose()
            Dim intNum As String = 0
            For Each obj As Control In TLP.Controls
                CType(obj, ucLHJ).StopServer()

                'CType(obj, ucLHJ).Dispose()
                intNum += 1
            Next
            'MsgBox(intNum)
            th_stop = False
            System.Threading.Thread.Sleep(3000)
            If th.IsAlive = True Then
                Try
                    th.Abort()
                Catch ex As Exception

                End Try

            End If
            System.Threading.Thread.Sleep(3000)
            Close()
        End If
    End Sub

    Private Sub frmLHJList_Closing(sender As Object, e As CancelEventArgs) Handles Me.Closing
        Me.Hide()
        e.Cancel = True
    End Sub

    Private Sub Log日志ToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles Log日志ToolStripMenuItem.Click
        Dim logForm As New FormLogNetView
        logForm.Show()
    End Sub

    Private Sub MoveDataTimer_Elapsed(sender As Object, e As ElapsedEventArgs) Handles MoveDataTimer.Elapsed

        If Now.ToShortTimeString.ToString.Equals("23:59") Then
            Dim objMove As New clsLHJWorkDetail
            objMove.dataMoveToHistory(Now)
        End If
    End Sub

    Private Sub NotifyIcon1_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles NotifyIcon1.MouseDoubleClick
        Me.Show()
    End Sub
End Class